
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

export default function useDeviceDetector() {
  const [isMobile, setIsMobile] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    const checkDevice = () => {
      const mobile = window.matchMedia('(max-width: 768px)').matches;
      setIsMobile(mobile);
      console.log('window.location.pathname', mobile, window.location.pathname);
      if (mobile && !window.location.pathname.startsWith('/mobile')) {
        navigate('/mobile' + window.location.pathname);
      } else if (!mobile && window.location.pathname.startsWith('/mobile')) {
        navigate(window.location.pathname.replace('/mobile', '') || '/');
      }
    };

    checkDevice();
    window.addEventListener('resize', checkDevice);
    return () => window.removeEventListener('resize', checkDevice);
  }, [navigate]);

  return isMobile;
}
